<template>
  <a-spin size="large" :spinning="spinloading">
    <div class="content_wrapper">
      <div>
        <a-card mb-4>
          <a-form :model="queryParams" :label-col="{ style: { width: '120px' } }" ref="queryForm">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item name="systemId" label="模板名称">
                  <a-input v-model:value="queryParams.systemId"/>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item name="bussinessId" label="模板编号">
                  <a-input v-model:value="queryParams.bussinessId"/>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item name="version" label="版本">
                  <a-input v-model:value="queryParams.version"/>
                </a-form-item>
              </a-col>

              <!--              <a-col :span="8">
                              <a-form-item name="fromVersion" label="上一个版本">
                                <a-input v-model:value="queryParams.fromVersion"/>
                              </a-form-item>
                            </a-col>-->


              <a-col :span="8">
                <a-form-item name="operatorBeginTime" label="操作开始时间">
                  <a-range-picker style="width: 100%" show-time v-model:value="queryDate.planStartTime"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  value-format="YYYY-MM-DD HH:mm:ss"></a-range-picker>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-space flex justify-end w-full>
                  <a-button :loading="loading" type="primary" @click="onSearch"> 查询</a-button>
                  <a-button :loading="loading" @click="onReset"> 重置</a-button>

                </a-space>
              </a-col>

            </a-row>

          </a-form>
        </a-card>

        <a-card>

          <template #title>
            <a-row>
              <a-space>
                <a-button type="primary" @click="handleAdd"> 新建模板</a-button>
              </a-space>
            </a-row>
          </template>

          <a-table :loading="loading"
                   :columns="columns" :row-key="(record) => record.id"
                   :scroll="{ x: '100%' }" :data-source="dataList" :pagination="pagination">
            <template #bodyCell="scope">
              <template v-if="scope?.column?.dataIndex === 'operatorName'">
                <div>
                  {{ scope.record.operatorName + scope.record.operator }}
                </div>
              </template>
              <template v-if="scope?.column?.dataIndex === 'mpUrl'">
                <a-typography-link @click="handleDownload(scope.record.mpUrl)"> {{
                    scope.record.mpUrl
                  }}
                </a-typography-link>
              </template>
              <template v-if="scope?.column?.dataIndex === 'action'">
                <div>
                  <a-space>
                    <a class="button" @click="() => handleView(scope.record)">查看</a>
                    <a class="button" @click="() => handleUpgrade(scope.record)">升版</a>
                    <a class="button" @click="() => handleHistory(scope.record)">历史版本</a>
                    <!--                    <a class="button"
                                           @click="() => handleUpdate(scope.record)">编辑</a>-->
                    <a type="text"
                       @click="() => handleDelete(scope.record)">删除</a>
                  </a-space>
                </div>
              </template>


            </template>
          </a-table>
        </a-card>

      </div>
    </div>

    <a-modal centered width="50%" v-model:open="open"
             @ok="confirmSubmit" @cancel="cancelModal"
             :title="mode === 'view'?'查看模板':(mode ==='upgrade'?'升级模板':'新建模板')">
      <div style="padding: 16px">
        <a-form ref="formRef" :model="formModel" :rules="rules"
                v-if="mode !== 'view'"
                :disabled="viewMode"
                :label-col="{ style: { width: '150px' } }"
                label-align="right">

          <a-form-item name="systemId" label="模板名称">
            <a-input :disabled="mode === 'upgrade' || mode === 'view'" v-model:value.trim="formModel.systemId"
                     placeholder="请输入"
                     allow-clear/>
          </a-form-item>
          <a-form-item name="bussinessId" label="模板编号">
            <a-input :disabled="mode === 'upgrade' || mode === 'view'" v-model:value.trim="formModel.bussinessId"
                     placeholder="请输入"
                     allow-clear/>
          </a-form-item>
          <a-form-item name="version" label="模板版本" v-if="mode !== 'upgrade' ||  mode === 'view'">
            <a-input disabled v-model:value="formModel.version" placeholder="请输入" allow-clear/>
          </a-form-item>

          <a-form-item name="fromVersion" label="上一个版本"  v-if="mode === 'upgrade' ">
            <a-input :disabled="mode === 'upgrade'"
                     v-model:value="formModel.fromVersion"
                     placeholder="请输入"/>
          </a-form-item>

          <a-form-item name="mpUrl" label="模板文件">
            <a-upload
                v-if="!viewMode"
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                :custom-request="customUpload"
                @remove="handleRemove"
            >
              <a-button>
                <upload-outlined/>
                选择文件
              </a-button>
            </a-upload>
            <div v-else>
              <a-typography-link @click="handleDownload(formModel.mpUrl)"> {{ formModel.mpUrl }}</a-typography-link>
            </div>
          </a-form-item>
          <a-form-item name="validStart" label="模板生效开始时间">
            <a-date-picker show-time v-model:value="formModel.validStart"
                           format="YYYY-MM-DD HH:mm:ss" :bordered="mode !== 'view'"
                           value-format="YYYY-MM-DD HH:MM:ss"></a-date-picker>
          </a-form-item>

          <a-form-item name="validEnd" label="模板生效结束时间">
            <a-date-picker show-time v-model:value="formModel.validEnd"
                           format="YYYY-MM-DD HH:mm:ss" :bordered="mode !== 'view'"
                           value-format="YYYY-MM-DD HH:mm:ss"></a-date-picker>
          </a-form-item>

        </a-form>

        <a-form ref="formRef" :model="formModel"
                v-else
                :disabled="viewMode"
                :label-col="{ style: { width: '150px' } }"
                label-align="right">

          <a-form-item name="systemId" label="模板名称">
            <a-input :disabled="mode === 'upgrade' || mode === 'view'" v-model:value.trim="formModel.systemId"
                     placeholder="请输入"
                     allow-clear :bordered="mode !== 'view'"/>
          </a-form-item>
          <a-form-item name="bussinessId" label="模板编号">
            <a-input :disabled="mode === 'upgrade' || mode === 'view'" v-model:value.trim="formModel.bussinessId"
                     placeholder="请输入"
                     allow-clear :bordered="mode !== 'view'"/>
          </a-form-item>
          <a-form-item name="version" label="模板版本" v-if="mode !== 'upgrade' ||  mode === 'view'">
            <a-input disabled v-model:value="formModel.version" placeholder="请输入" :bordered="mode !== 'view'"
                     allow-clear/>
          </a-form-item>

          <a-form-item name="fromVersion" label="上一个版本" v-if="mode === 'view' ">
            <a-input readOnly :bordered="false"
                     v-model:value="formModel.fromVersion"/>

          </a-form-item>

          <a-form-item name="mpUrl" label="模板文件">
            <a-upload
                v-if="!viewMode"
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                :custom-request="customUpload"
                @remove="handleRemove"
            >
              <a-button>
                <upload-outlined/>
                选择文件
              </a-button>
            </a-upload>
            <div v-else>
              <a-typography-link @click="handleDownload(formModel.mpUrl)"> {{ formModel.mpUrl }}</a-typography-link>
            </div>
          </a-form-item>
          <a-form-item name="validStart" label="模板生效开始时间">
            <a-input show-time v-model:value="formModel.validStart"
                     format="YYYY-MM-DD HH:mm:ss" :bordered="mode !== 'view'"
                     value-format="YYYY-MM-DD HH:MM:ss"></a-input>
          </a-form-item>

          <a-form-item name="validEnd" label="模板生效结束时间">
            <a-input show-time v-model:value="formModel.validEnd"
                     format="YYYY-MM-DD HH:mm:ss" :bordered="mode !== 'view'"
                     value-format="YYYY-MM-DD HH:mm:ss"></a-input>
          </a-form-item>

          <!--          <a-form-item name="type" label="码段类型">
                      <a-select v-model:value="formModel.type" @change="typeChange">
                        <a-select-option v-for="item in options.type" placeholder="请选择"
                                         :key="item.value"
                                         :value="item.value">{{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-item>-->


        </a-form>

      </div>
    </a-modal>

    <a-modal centered width="50%" v-model:open="openHistory"
             :title="'历史版本'">
      <div style="padding: 16px;overflow: auto;max-height: 50vh;">
        <a-timeline v-if="historyList.length">
          <a-timeline-item :color="index===0?'green':'gray'" v-for="(item,index) in historyList" :key="index">
            <a-descriptions :column="1">
              <a-descriptions-item label="模板版本">{{ item.version }}</a-descriptions-item>
              <a-descriptions-item label="模板名称">{{ item.systemId }}</a-descriptions-item>
              <a-descriptions-item label="模板编号">{{ item.bussinessId }}</a-descriptions-item>
              <a-descriptions-item label="上一个版本">{{ item.fromVersion }}</a-descriptions-item>
              <a-descriptions-item label="模板文件">
                <a-typography-link @click="handleDownload(item.mpUrl)"> {{ item.mpUrl }}</a-typography-link>
              </a-descriptions-item>
              <a-descriptions-item label="模板生效开始时间">{{ item.validStart }}</a-descriptions-item>
              <a-descriptions-item label="模板生效结束时间">{{ item.validEnd }}</a-descriptions-item>

            </a-descriptions>
          </a-timeline-item>
        </a-timeline>
        <a-empty v-else description="暂无历史版本"></a-empty>

      </div>
      <template #footer>
        <a-button type="primary" @click="openHistory=false">关闭</a-button>
      </template>
    </a-modal>

  </a-spin>
</template>

<script lang="ts" setup>
import {computed, createVNode, onMounted, reactive, ref, shallowRef} from 'vue'
import type {PaginationProps} from 'ant-design-vue'
import {message, Modal, Upload} from 'ant-design-vue'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import {UploadOutlined} from "@ant-design/icons-vue";
import moment from 'moment'

import * as api from './service'

import {
  DownOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import {useI18n} from 'vue-i18n'
import {getTemplateHistory} from "./service";

const {t} = useI18n()
const spinloading = ref<Boolean>(false)

const columns = shallowRef([
  {
    title: '序号',
    dataIndex: 'no',
    width: 60,
    customRender: ({text, record, index}) => {
      return index + 1
    }
  },
  {title: '模板名称', dataIndex: 'systemId', ellipsis: true},
  {title: '模板编号', dataIndex: 'bussinessId', ellipsis: true},
  {title: '版本', dataIndex: 'version', ellipsis: true},
  // {title: '上一个版本', dataIndex: 'fromVersion', ellipsis: true},
  {title: '模板地址', dataIndex: 'mpUrl', ellipsis: true},
  {title: '模板生效开始', dataIndex: 'validStart', ellipsis: true},
  {title: '模板生效结束', dataIndex: 'validEnd', ellipsis: true},
  {title: '操作人', dataIndex: 'operator', width: 100, ellipsis: true},
  {title: '操作时间', dataIndex: 'operatorTime', width: 160, ellipsis: true},
  {title: '操作', dataIndex: 'action', width: 200}

])

const options = reactive({
  rules: [],
  taskStatus: [
    {
      label: '等待执行',
      value: 0
    },
    {
      label: '正在执行',
      value: 1
    },
    {
      label: '执行成功',
      value: 2
    },
    {
      label: '执行失败',
      value: 3
    }
  ]

})

const queryForm = ref()
const dataList = ref<Array>([])
const total = ref<Number>(0)
const loading = ref<Boolean>(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 0,
  showSizeChanger: true,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    getListData()
  },
  showTotal: (total) => `共${total}条`
})
const selectedRowKeys = ref([])
const rowSelections = computed(() => {
  return {
    selectedRowKeys: selectedRowKeys,
    onChange: (val) => {
      selectedRowKeys.value = val
    }
  }
})
const expand = ref(false)
//查询参数
const queryDate = ref({
  planStartTime: null,
  planEndTime: null
})
const queryParams = ref({})
//弹窗
const open = ref(false)
const viewMode = ref(false)
const mode = ref('')
const formModel = ref({})
const formRef = ref()
const fileList = ref([])
// 校验规则
const rules = {
  systemId: [{required: true, message: '不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {
        if (value && value.trim().length > 100) {
          return Promise.reject('不能超过100字符')
        }
        const reg = /^[a-zA-Z0-9_-]*$/;
        if(value && !reg.test(value)) {
          return Promise.reject('输入内容只能包含数字、大小写字母、下划线和横线')

        }
        return Promise.resolve()
      }, trigger: 'change'
    }
  ],
  bussinessId: [{required: true, message: '不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {
        if (value && value.trim().length > 100) {
          return Promise.reject('名不能超过100字符')
        }
        const reg = /^[a-zA-Z0-9_-]*$/;
        if(value && !reg.test(value)) {
          return Promise.reject('输入只能包含数字、大小写字母、下划线和横线')

        }
        return Promise.resolve()
      }, trigger: 'change'
    }],
  version: [{required: true, message: '不能为空', trigger: 'change'}],
  fromVersion: [{required: true, message: '不能为空', trigger: 'change'}],
  mpUrl: [{required: true, message: '不能为空', trigger: 'change/blur'}],
  validStart: [{required: true, message: '模板生效开始时间不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {

        if (formModel.value.validStart && formModel.value.validEnd) {
          if (moment(formModel.value.validStart).isSameOrAfter(moment(formModel.value.validEnd))) {
            return Promise.reject('开始时间不能晚于结束时间');
          }
        }
        return Promise.resolve()
      }, trigger: 'change'
    }
  ],
  validEnd: [
    {required: true, message: '模板生效结束时间不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {
        if (formModel.value.validStart && formModel.value.validEnd) {
          if (moment(formModel.value.validStart).isSameOrAfter(moment(formModel.value.validEnd))) {
            return Promise.reject('开始时间不能晚于结束时间');
          }
        }
        return Promise.resolve()
      }, trigger: 'change'
    }
  ],


}
const getListData: (param: Boolean) => void = async () => {
  loading.value = true

  let params = {
    ...queryParams.value,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  if (queryDate.value.planStartTime && queryDate.value.planStartTime.length) {
    console.log(queryDate.value.planStartTime)
    params.operatorBeginTime = queryDate.value.planStartTime[0]
    params.operatorEndTime = queryDate.value.planStartTime[1]
  }
  const res = await api.listTemplate(params)
  dataList.value = res.data
  pagination.total = res.totalCount
  loading.value = false
}

onMounted(() => {
  getOptions()
  getListData()
})

function getOptions() {

}

async function onSearch() {
  pagination.current = 1
  await getListData()
}

function clear() {
  selectedRowKeys.value = []

  getListData()
}

async function onReset() {
  // 清空所有参数重新请
  formRef.value?.resetFields()
  queryDate.value = {
    planStartTime: null,
    planEndTime: null
  }
  queryParams.value = {}
  await getListData()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record) {
  if (!selectedRowKeys.value.length && !record) {
    message.error('请选择数据！')
    return
  }
  const modal = Modal.confirm({
    content: '确认删除当前任务吗？',
    icon: createVNode(ExclamationCircleOutlined),
    onOk() {
      console.log(selectedRowKeys.value)

      if (record?.id) {
        api.deleteTemplate(record.id).then(value => {
          message.success('删除成功！')
          getListData()
        })
      } else {
        api.batchDeleteTemplate(selectedRowKeys.value).then(value => {
          message.success('删除成功！')
          selectedRowKeys.value = []
          getListData()
        })
      }

    },
    onCancel() {
      modal.destroy()
    }
  })
}

function handleView(record) {
  viewMode.value = true
  mode.value = 'view'
  api.getTemplate(record.id).then(res => {
    formModel.value = res.data
    fileList.value = [{
      name: formModel.value.mpUrl,
      url: formModel.value.mpUrl
    }]

    open.value = true


  })
}

async function handleDownload(mpUrl) {
  spinloading.value = true
  try {
    const link = document.createElement('a')
    link.href = mpUrl
    // link.download = (record.systemName + '.zip') || 'file.zip' // 指定文件名，可选默认值
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

  } finally {
    spinloading.value = false
  }

}

function beforeUpload(file) {
  const isSizeValid = file.size / 1024 / 1024 < 100;
  if (!isSizeValid) {
    message.error('文件大小不能超过100MB');
    return Upload.LIST_IGNORE;
  }

  // 校验文件后缀名是否为 .ftl
  const isValidExtension = file.name.split('.').pop().toLowerCase() === 'ftl';

  if (!isValidExtension) {
    message.error('只能上传 .ftl 类型的文件！');
    return Upload.LIST_IGNORE;

  }

  return true;
}

const customUpload = async ({file, onProgress, onSuccess, onError}) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const res = await api.uploadTemplate(formData, {
      onUploadProgress: e => {
        onProgress({percent: (e.loaded / e.total) * 100});
      },
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    onSuccess(res.data, file);
    fileList.value = [file]
    formModel.value.mpUrl = res.data

  } catch (error) {
    onError(error);
  }
}

function handleRemove() {
  fileList.value = []
  formModel.value.mpUrl = null

}

function handleAdd() {
  mode.value = 'add'
  viewMode.value = false
  formRef.value?.resetFields()

  open.value = true
  formModel.value = {}
  fileList.value = []
  formModel.value.version = '001'

}

function handleUpgrade(record) {
  mode.value = 'upgrade'
  formRef.value?.resetFields()

  api.getTemplate(record.id).then(res => {
    const obj = res.data

    formModel.value = {
      id: obj.id,
      systemId: obj.systemId,
      bussinessId: obj.bussinessId,
      fromVersion: obj.version,
    }
    fileList.value = []

    open.value = true


  })
}


function handleUpdate(record) {
  mode.value = 'update'
  api.getTemplate(record.id).then(res => {
    formModel.value = res.data
    fileList.value = [{
      name: formModel.value.mpUrl,
      url: formModel.value.mpUrl
    }]

    open.value = true


  })
}

async function confirmSubmit() {

  formRef.value.validate().then(async () => {

    if (mode.value === 'upgrade') {
      await api.upgradeTemplate({
        ...formModel.value
      }).catch(() => {

      });
    } else if (mode.value === 'update') {
      await api.updateTemplate({
        ...formModel.value
      }).catch(() => {

      });
    } else if (mode.value === 'add') {
      await api.createTemplate({
        ...formModel.value
      }).catch(() => {

      })
    }

    message.success('保存成功')
    cancelModal()

  })
}

function cancelModal() {
  open.value = false
  viewMode.value = false

  getListData()
}


const openHistory = ref(false)
const historyList = ref([])


function handleHistory(record) {
  api.getTemplateHistory(record.bussinessId, record.systemId).then(res => {
    const obj = res.data
    obj.sort((a, b) => b.id - a.id)
    historyList.value = obj
    openHistory.value = true

  })
}
</script>

<style lang="less" scoped>
.content_wrapper {
}

.form_search {
  padding: 16px 10px;
}

.ant-uploader {
  padding: 12px;
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  align-items: center;

  /deep/ .ant_upload_class {
    width: 100%;
  }

  /deep/ .ant-upload {
    width: 100%;
  }

  .upload_area {
    width: 100%;
    height: 200px;
    border: 1px dotted #999999;
    display: flex;

    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .action-icon {
    font-size: 50px;
    color: #999;
    text-align: center;
  }

  .ant-upload-text {
    margin-top: 8px;
    color: #666666;
    text-align: center;
  }

  /deep/ .ant-upload-list-item-name {
    text-wrap: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
